package services

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
	"time"
)

const (
	maxRetries     = 3
	requestTimeout = 10 * time.Second
	retryWaitTime  = 1 * time.Second
)

// 频道类型常量
const (
	ChannelTypeClaudeMin   = "Claude"
	ChannelTypePlus        = "Plus"
	ChannelTypeFingerprint = "Fingerprint" // 将Free改为指纹频道
)

// API服务URL配置
var (
	ClaudeBaseURL      = ""
	PlusBaseURL        = ""
	FingerprintBaseURL = "http://localhost:8080" // 指纹API基础URL
)

// 初始化API服务URLs
func InitAPIURLs(claudeURL, plusURL string, fingerprintURL string) {
	ClaudeBaseURL = claudeURL
	PlusBaseURL = plusURL
	FingerprintBaseURL = fingerprintURL
}

var client = &http.Client{
	Timeout: requestTimeout,
}

type CarPageRequest struct {
	Page  int    `json:"page"`
	Size  int    `json:"size"`
	Email string `json:"email,omitempty"` // 添加Email字段用于指纹API
}

// 指纹浏览器信息结构体
type BrowserInfo struct {
	CarID           string `json:"carID"`
	BrowserName     string `json:"browserName"`
	BrowserType     string `json:"browserType"`
	BrowserTargName string `json:"browserTargName"`
	ExpirationTime  string `json:"expirationTime"`
	IsPlus          int    `json:"isPlus"`
	Status          int    `json:"status"`
}

// 指纹浏览器响应结构体
type FingerprintBrowserResponse struct {
	Code     int    `json:"code"`
	Messages string `json:"messages"`
	Notice   string `json:"notice"`
	Data     struct {
		List       []BrowserInfo `json:"list"`
		Pagination struct {
			Page  int `json:"page"`
			Size  int `json:"size"`
			Total int `json:"total"`
		} `json:"pagination"`
	} `json:"data"`
}

type CarPageResponse struct {
	Code     int    `json:"code"`
	Messages string `json:"messages"`
	Notice   string `json:"notice"`
	Data     struct {
		List []struct {
			CarID  string `json:"carID"`
			Label  string `json:"browserTargName"`
			Name   string `json:"browserName"`
			IsPlus int    `json:"isPlus"`
			Status int    `json:"status"`
		} `json:"list"`
		Pagination struct {
			Page  int `json:"page"`
			Size  int `json:"size"`
			Total int `json:"total"`
		} `json:"pagination"`
	} `json:"data"`
}

type EndpointResponse struct {
	Color         string `json:"color"`
	Label         string `json:"label"`
	LabelColor    string `json:"labelColor"`
	Message       string `json:"message"`
	NamedLogo     string `json:"namedLogo"`
	SchemaVersion int    `json:"schemaVersion"`
}

// 获取数据源URL
func getBaseURLForChannelType(channelType string) string {
	switch channelType {
	case ChannelTypeClaudeMin:
		return ClaudeBaseURL
	case ChannelTypePlus:
		return PlusBaseURL
	case ChannelTypeFingerprint:
		return FingerprintBaseURL
	default:
		return ClaudeBaseURL // 默认使用Claude源
	}
}

// 带重试的HTTP POST请求
func retryPost(url string, jsonData []byte) (*http.Response, error) {
	var lastErr error
	for i := 0; i < maxRetries; i++ {
		req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonData))
		if err != nil {
			return nil, err
		}
		req.Header.Set("Content-Type", "application/json")

		resp, err := client.Do(req)
		if err == nil {
			return resp, nil
		}
		lastErr = err
		time.Sleep(retryWaitTime)
	}
	return nil, fmt.Errorf("after %d retries: %v", maxRetries, lastErr)
}

// 带重试的HTTP GET请求
func retryGet(url string) (*http.Response, error) {
	var lastErr error
	for i := 0; i < maxRetries; i++ {
		req, err := http.NewRequest("GET", url, nil)
		if err != nil {
			return nil, err
		}

		resp, err := client.Do(req)
		if err == nil {
			return resp, nil
		}
		lastErr = err
		time.Sleep(retryWaitTime)
	}
	return nil, fmt.Errorf("after %d retries: %v", maxRetries, lastErr)
}

// 获取特定频道类型的卡片列表
func GetCarPageByType(channelType string, page, size int, email string) (*CarPageResponse, error) {
	baseURL := getBaseURLForChannelType(channelType)

	// 处理指纹频道的特殊情况
	if channelType == ChannelTypeFingerprint {
		return GetFingerprintCarPage(page, size, email)
	}

	reqBody := CarPageRequest{
		Page: page,
		Size: size,
	}

	jsonData, err := json.Marshal(reqBody)
	if err != nil {
		return nil, err
	}

	resp, err := retryPost(baseURL+"/carpage", jsonData)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result CarPageResponse
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return nil, err
	}

	if result.Code != 1000 {
		return nil, fmt.Errorf("API error: %s", result.Messages)
	}

	return &result, nil
}

// 获取指纹频道数据
func GetFingerprintCarPage(page, size int, email string) (*CarPageResponse, error) {
	// 如果email为空，表示是游客，直接返回空列表
	if email == "" {
		// 创建一个空的响应
		result := &CarPageResponse{
			Code:     1000,
			Messages: "success",
			Notice:   "",
		}
		// 初始化空列表
		result.Data.List = make([]struct {
			CarID  string `json:"carID"`
			Label  string `json:"browserTargName"`
			Name   string `json:"browserName"`
			IsPlus int    `json:"isPlus"`
			Status int    `json:"status"`
		}, 0)
		// 设置分页信息
		result.Data.Pagination.Page = page
		result.Data.Pagination.Size = size
		result.Data.Pagination.Total = 0

		return result, nil
	}

	// 调用指纹浏览器API
	browsers, err := GetFingerprintBrowsers(email, page, size)
	if err != nil {
		return nil, err
	}

	// 转换为标准的CarPageResponse格式
	result := &CarPageResponse{
		Code:     browsers.Code,
		Messages: browsers.Messages,
		Notice:   browsers.Notice,
	}

	// 初始化列表
	result.Data.List = make([]struct {
		CarID  string `json:"carID"`
		Label  string `json:"browserTargName"`
		Name   string `json:"browserName"`
		IsPlus int    `json:"isPlus"`
		Status int    `json:"status"`
	}, 0, len(browsers.Data.List))

	// 转换列表数据
	for _, browser := range browsers.Data.List {
		result.Data.List = append(result.Data.List, struct {
			CarID  string `json:"carID"`
			Label  string `json:"browserTargName"`
			Name   string `json:"browserName"`
			IsPlus int    `json:"isPlus"`
			Status int    `json:"status"`
		}{
			CarID:  browser.CarID,
			Label:  browser.BrowserTargName, // 映射 BrowserTargName 到 Label
			Name:   browser.BrowserName,     // 映射 BrowserName 到 Name
			IsPlus: browser.IsPlus,
			Status: browser.Status,
		})
	}

	// 设置分页信息
	result.Data.Pagination = browsers.Data.Pagination

	return result, nil
}

// 获取指纹浏览器信息
func GetFingerprintBrowsers(email string, page, size int) (*FingerprintBrowserResponse, error) {
	reqBody := CarPageRequest{
		Page:  page,
		Size:  size,
		Email: email,
	}

	jsonData, err := json.Marshal(reqBody)
	if err != nil {
		return nil, err
	}

	resp, err := retryPost(FingerprintBaseURL+"/api/external/user-browsers", jsonData)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result FingerprintBrowserResponse
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return nil, err
	}

	if result.Code != 1000 {
		return nil, fmt.Errorf("API error: %s", result.Messages)
	}

	return &result, nil
}

// 获取所有频道类型的卡片列表 (兼容旧代码)
func GetCarPage(page, size int) (*CarPageResponse, error) {
	return GetCarPageByType(ChannelTypeClaudeMin, page, size, "")
}

// 获取卡片状态
func GetEndpointStatus(channelType string, carID string) (*EndpointResponse, error) {
	baseURL := getBaseURLForChannelType(channelType)

	// 处理指纹频道的特殊情况
	if channelType == ChannelTypeFingerprint {
		// 对于指纹频道，返回默认的状态信息
		return &EndpointResponse{
			Color:         "green",
			Label:         "可用",
			LabelColor:    "green",
			Message:       "指纹浏览器可用",
			NamedLogo:     "fingerprint",
			SchemaVersion: 1,
		}, nil
	}

	resp, err := retryGet(fmt.Sprintf("%s/endpoint?carid=%s", baseURL, carID))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result EndpointResponse
	if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
		return nil, err
	}

	return &result, nil
}

// 转换API响应到Channel模型
func ConvertToChannel(channelType string, carInfo struct {
	CarID  string `json:"carID"`
	Label  string `json:"browserTargName"`
	Name   string `json:"browserName"`
	IsPlus int    `json:"isPlus"`
	Status int    `json:"status"`
}, status *EndpointResponse, email string) Channel {

	// 根据status.color和message确定状态
	channelStatus := "UNKNOWN"
	statusClass := "error" // 默认为error类

	// 这里对状态进行更细致的判断
	if status.Color == "green" {
		channelStatus = "FREE"
		statusClass = "idle"
	} else if status.Color == "yellow" || status.Color == "orange" {
		channelStatus = "BUSY"
		statusClass = "busy"
	} else if status.Color == "red" {
		channelStatus = "ERROR"
		statusClass = "error"
	}

	// 也可以通过message做额外判断
	if strings.Contains(status.Message, "空闲") {
		channelStatus = "FREE"
		statusClass = "idle"
	} else if strings.Contains(status.Message, "繁忙") {
		channelStatus = "BUSY"
		statusClass = "busy"
	} else if strings.Contains(status.Message, "翻车") ||
		strings.Contains(status.Message, "不可用") ||
		strings.Contains(status.Message, "超车不可用") {
		channelStatus = "ERROR"
		statusClass = "error"
	}

	name := carInfo.CarID

	// 如果是指纹频道，使用Label和Name字段构建更友好的名称
	if channelType == ChannelTypeFingerprint && carInfo.Label != "" && carInfo.Name != "" {
		name = fmt.Sprintf("%s - %s", carInfo.Label, carInfo.Name)
	}

	return Channel{
		ID:          carInfo.CarID,
		Name:        name,
		Type:        channelType,
		Status:      channelStatus,
		StatusClass: statusClass,
		Key:         carInfo.CarID,
		RealStatus:  status.Message,
		IdleStatus:  status.Label,
	}
}

// 根据ID获取指纹浏览器信息
func GetFingerprintBrowserById(carID string, email string) (*BrowserInfo, error) {
	// 如果email为空，表示是游客，直接返回错误
	if email == "" {
		return nil, fmt.Errorf("user is guest, cannot get browser info")
	}

	// 获取所有浏览器
	browsers, err := GetFingerprintBrowsers(email, 1, 100)
	if err != nil {
		return nil, err
	}

	// 查找匹配的浏览器
	for _, browser := range browsers.Data.List {
		if browser.CarID == carID {
			return &browser, nil
		}
	}

	return nil, fmt.Errorf("browser not found with ID: %s", carID)
}

// 简单的字符串包含判断函数
func contains(s, substr string) bool {
	return strings.Contains(s, substr)
}
